/**
 * 数据源连接测试模态框组件
 * 用于测试数据源连接状态和查看测试历史
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Modal,
  Button,
  Alert,
  Descriptions,
  Table,
  Space,
  Tag,
  Spin,
  Empty,
  Tooltip,
  Typography
} from 'antd';
import {
  ExperimentOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  InfoCircleOutlined,
  HistoryOutlined,
  ReloadOutlined
} from '@ant-design/icons';

import type {
  DataSource,
  ConnectionTestResponse,
  TestLog
} from '../types/datasource';
import {
  TestStatus,
  TestStatusLabels,
  TestStatusColors
} from '../types/datasource';
import { datasourceApi } from '../services/datasourceApi';

const { Text } = Typography;

interface DataSourceTestModalProps {
  /** 是否显示模态框 */
  visible: boolean;
  /** 要测试的数据源 */
  dataSource?: DataSource;
  /** 关闭模态框回调 */
  onClose: () => void;
}

const DataSourceTestModal: React.FC<DataSourceTestModalProps> = ({
  visible,
  dataSource,
  onClose
}) => {
  const [testLoading, setTestLoading] = useState(false);
  const [testResult, setTestResult] = useState<ConnectionTestResponse | null>(null);
  const [logsLoading, setLogsLoading] = useState(false);
  const [testLogs, setTestLogs] = useState<TestLog[]>([]);
  const [logsTotal, setLogsTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [activeTab, setActiveTab] = useState<'test' | 'history'>('test');

  // 重置状态
  const resetState = useCallback(() => {
    setTestResult(null);
    setTestLogs([]);
    setLogsTotal(0);
    setCurrentPage(1);
    setActiveTab('test');
  }, []);

  // 模态框打开时重置状态
  useEffect(() => {
    if (visible && dataSource) {
      resetState();
    }
  }, [visible, dataSource, resetState]);

  // 执行连接测试
  const handleTest = useCallback(async () => {
    if (!dataSource) return;

    setTestLoading(true);
    setTestResult(null);

    try {
      const result = await datasourceApi.testDatasourceConnection(dataSource.id);
      setTestResult(result);
    } catch (error) {
      // 错误已在API服务中处理
      setTestResult({
        success: false,
        message: '连接测试失败',
        error_details: { error_message: '网络错误或服务不可用' }
      });
    } finally {
      setTestLoading(false);
    }
  }, [dataSource]);

  // 加载测试历史
  const loadTestLogs = useCallback(async (page: number = 1) => {
    if (!dataSource) return;

    setLogsLoading(true);

    try {
      const result = await datasourceApi.getDatasourceTestLogs(dataSource.id, page, 10);
      setTestLogs(result.logs);
      setLogsTotal(result.total);
      setCurrentPage(page);
    } catch (error) {
      // 错误已在API服务中处理
    } finally {
      setLogsLoading(false);
    }
  }, [dataSource]);

  // 切换到历史标签时加载数据
  const handleTabChange = useCallback((tab: 'test' | 'history') => {
    setActiveTab(tab);
    if (tab === 'history' && testLogs.length === 0) {
      loadTestLogs(1);
    }
  }, [testLogs.length, loadTestLogs]);

  // 测试日志表格列配置
  const logColumns = [
    {
      title: '测试时间',
      dataIndex: 'tested_at',
      key: 'tested_at',
      width: 180,
      render: (value: string) => new Date(value).toLocaleString()
    },
    {
      title: '测试状态',
      dataIndex: 'test_status',
      key: 'test_status',
      width: 100,
      render: (status: TestStatus) => (
        <Tag
          color={TestStatusColors[status]}
          icon={status === TestStatus.SUCCESS ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
        >
          {TestStatusLabels[status]}
        </Tag>
      )
    },
    {
      title: '响应时间',
      dataIndex: 'response_time',
      key: 'response_time',
      width: 100,
      render: (time: number | null) => time ? `${time}ms` : '-'
    },
    {
      title: '测试消息',
      dataIndex: 'test_message',
      key: 'test_message',
      ellipsis: {
        showTitle: false
      },
      render: (message: string) => (
        <Tooltip title={message} placement="topLeft">
          <Text ellipsis>{message || '-'}</Text>
        </Tooltip>
      )
    }
  ];

  if (!dataSource) {
    return null;
  }

  return (
    <Modal
      title={
        <Space>
          <ExperimentOutlined />
          数据源连接测试 - {dataSource.display_name}
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={null}
      destroyOnClose
    >
      {/* 标签切换 */}
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button
            type={activeTab === 'test' ? 'primary' : 'default'}
            icon={<ExperimentOutlined />}
            onClick={() => handleTabChange('test')}
          >
            连接测试
          </Button>
          <Button
            type={activeTab === 'history' ? 'primary' : 'default'}
            icon={<HistoryOutlined />}
            onClick={() => handleTabChange('history')}
          >
            测试历史
          </Button>
        </Space>
      </div>

      {/* 连接测试标签 */}
      {activeTab === 'test' && (
        <div>
          {/* 数据源基本信息 */}
          <Descriptions
            title="数据源信息"
            bordered
            size="small"
            column={2}
            style={{ marginBottom: 16 }}
          >
            <Descriptions.Item label="数据源名称">
              {dataSource.display_name}
            </Descriptions.Item>
            <Descriptions.Item label="数据库类型">
              {dataSource.type.toUpperCase()}
            </Descriptions.Item>
            <Descriptions.Item label="连接地址">
              {dataSource.connection_string_masked}
            </Descriptions.Item>
            <Descriptions.Item label="当前状态">
              <Tag
                color={dataSource.is_healthy ? 'success' : 'error'}
                icon={dataSource.is_healthy ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
              >
                {dataSource.is_healthy ? '健康' : '异常'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="最后测试时间">
              {dataSource.last_test_at 
                ? new Date(dataSource.last_test_at).toLocaleString()
                : '从未测试'
              }
            </Descriptions.Item>
            <Descriptions.Item label="最后测试状态">
              <Tag color={TestStatusColors[dataSource.last_test_status]}>
                {TestStatusLabels[dataSource.last_test_status]}
              </Tag>
            </Descriptions.Item>
          </Descriptions>

          {/* 测试按钮 */}
          <div style={{ textAlign: 'center', marginBottom: 16 }}>
            <Button
              type="primary"
              size="large"
              icon={<ExperimentOutlined />}
              loading={testLoading}
              onClick={handleTest}
            >
              {testLoading ? '正在测试...' : '开始测试连接'}
            </Button>
          </div>

          {/* 测试结果 */}
          {testResult && (
            <Alert
              type={testResult.success ? 'success' : 'error'}
              message={
                <Space>
                  {testResult.success ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
                  {testResult.message}
                </Space>
              }
              description={
                <div>
                  {testResult.success ? (
                    <div>
                      {testResult.response_time && (
                        <div>
                          <Text strong>响应时间:</Text> {testResult.response_time}ms
                        </div>
                      )}
                      {testResult.database_info && (
                        <div style={{ marginTop: 8 }}>
                          <Text strong>数据库信息:</Text>
                          <ul style={{ margin: '4px 0 0 16px' }}>
                            <li>类型: {testResult.database_info.database_type}</li>
                            <li>版本: {testResult.database_info.version}</li>
                            <li>当前数据库: {testResult.database_info.current_database}</li>
                          </ul>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div>
                      {testResult.error_details?.error_message && (
                        <div>
                          <Text strong>错误信息:</Text> {testResult.error_details.error_message}
                        </div>
                      )}
                      {testResult.response_time && (
                        <div style={{ marginTop: 4 }}>
                          <Text strong>响应时间:</Text> {testResult.response_time}ms
                        </div>
                      )}
                    </div>
                  )}
                </div>
              }
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
        </div>
      )}

      {/* 测试历史标签 */}
      {activeTab === 'history' && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <h4 style={{ margin: 0 }}>
              <HistoryOutlined style={{ marginRight: 8 }} />
              测试历史记录
            </h4>
            <Button
              icon={<ReloadOutlined />}
              onClick={() => loadTestLogs(currentPage)}
              loading={logsLoading}
              size="small"
            >
              刷新
            </Button>
          </div>

          <Spin spinning={logsLoading}>
            {testLogs.length > 0 ? (
              <Table
                columns={logColumns}
                dataSource={testLogs}
                rowKey="id"
                size="small"
                pagination={{
                  current: currentPage,
                  pageSize: 10,
                  total: logsTotal,
                  showSizeChanger: false,
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                  onChange: loadTestLogs
                }}
              />
            ) : (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description="暂无测试记录"
              />
            )}
          </Spin>
        </div>
      )}

      {/* 底部操作按钮 */}
      <div style={{ textAlign: 'right', marginTop: 16, paddingTop: 16, borderTop: '1px solid #f0f0f0' }}>
        <Button onClick={onClose}>
          关闭
        </Button>
      </div>
    </Modal>
  );
};

export default DataSourceTestModal;
